<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" width="750px" :title="`${dialogProps.title}礼券发放`">
    <el-form
      ref="ruleFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="rules"
      :disabled="dialogProps.isView"
      :model="dialogProps.row"
      :hide-required-asterisk="dialogProps.isView"
    >
      <el-row :gutter="20" v-if="dialogProps.title !== '批量新增'">
        <el-col :span="12">
          <el-form-item label="礼券编码" prop="couponCode">
            <el-input v-model="dialogProps.row!.couponCode" disabled />
          </el-form-item>
          <el-form-item label="礼券名称" prop="couponId">
            <el-input v-model="dialogProps.row!.couponName" disabled>
              <template #append>
                <el-button :icon="MoreFilled" @click="openSelectTreeTable('选择优惠券', 0)" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="礼券类型" prop="typeId">
            <el-select class="w100" v-model="dialogProps.row!.typeId" disabled>
              <el-option v-for="item in giftVoucherType" :key="item.value" :label="item.title" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="礼券面额" prop="parValue">
            <el-input v-model="dialogProps.row!.parValue" disabled></el-input>
          </el-form-item>
          <el-form-item label="	发放时间" prop="distributionDate">
            <el-date-picker class="w100" v-model="dialogProps.row!.distributionDate" type="date" format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="发放人" prop="createUserName">
            <el-input v-model="dialogProps.row!.createUserName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开始领取时间" prop="collectionStartDate">
            <el-date-picker class="w100" v-model="dialogProps.row!.collectionStartDate" type="date" format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="结束领取时间" prop="collectionEndDate">
            <el-date-picker class="w100" v-model="dialogProps.row!.collectionEndDate" type="date" format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="礼券状态" prop="status">
            <el-select class="w100" v-model="dialogProps.row!.status">
              <el-option v-for="item in foodCouponUserStatus" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="绑定会员" prop="userName">
            <el-input v-model="dialogProps.row!.userName" disabled>
              <template #append>
                <el-button :icon="MoreFilled" @click="openSelectTreeTable('选择会员', 1)" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="dialogProps.row!.remarks" placeholder="请输入" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-else>
        <el-col :span="12">
          <el-form-item label="礼券名称" prop="couponId">
            <el-input v-model="dialogProps.row!.couponName" disabled>
              <template #append>
                <el-button :icon="MoreFilled" @click="openSelectTreeTable('选择优惠券', 0)" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="起始编码" prop="startCode">
            <el-input-number v-model="dialogProps.row!.startCode" :controls="false" class="w100" />
          </el-form-item>
          <el-form-item label="首字符" prop="fristChar">
            <el-input v-model="dialogProps.row!.fristChar" />
          </el-form-item>
          <el-form-item label="开始领取时间" prop="collectionStartDate">
            <el-date-picker class="w100" v-model="dialogProps.row!.collectionStartDate" type="date" format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="发放日期" prop="distributionDate">
            <el-date-picker class="w100" v-model="dialogProps.row!.distributionDate" type="date" format="YYYY-MM-DD" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="制作张数" prop="count">
            <el-input-number class="w100" v-model="dialogProps.row!.count" :controls="false" />
          </el-form-item>
          <!-- <el-form-item label="终止编码" prop="endCode">
            <el-input v-model="dialogProps.row!.endCode" />
          </el-form-item> -->
          <el-form-item label="结尾字符" prop="endChar">
            <el-input v-model="dialogProps.row!.endChar" />
          </el-form-item>
          <el-form-item label="结束领取时间" prop="collectionEndDate">
            <el-date-picker class="w100" v-model="dialogProps.row!.collectionEndDate" type="date" format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="消费密码" prop="password">
            <el-input v-model="dialogProps.row!.password" />
          </el-form-item>
          <el-form-item label="绑定会员" prop="userName">
            <el-input v-model="dialogProps.row!.userName" disabled>
              <template #append>
                <el-button :icon="MoreFilled" @click="openSelectTreeTable('选择会员', 1)" />
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <SelectTable @radio="onRadio" ref="selectTableRef" />
    <template #footer>
      <el-button @click="dialogVisible = false"> 取消 </el-button>
      <el-button v-show="!dialogProps.isView" type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="UserCategoryDialog">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { MoreFilled } from "@element-plus/icons-vue";
import { Member } from "@/api/interface";
import { getFoodCouponUserCode, getFoodCouponList } from "@/api/modules/coupon";
import { foodCouponUserStatus } from "@/utils/serviceDict";
import SelectTable from "@/components/SelectTable/index.vue";
import { getDicData } from "@/api/modules/system";
import { getMemberList } from "@/api/modules/member";

const rules = reactive({
  couponId: [{ required: true, message: "请选择礼券" }],
  distributionDate: [{ required: true, message: "请设发放时间" }],
  collectionStartDate: [{ required: true, message: "请设置开始领取时间" }],
  collectionEndDate: [{ required: true, message: "请设置结束领取时间" }]
});

interface DialogProps {
  title: string;
  isView: boolean;
  row: Partial<Member.ResMemberGradeList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const dialogVisible = ref(false);
const giftVoucherType = ref([]);
const dialogProps = ref<DialogProps>({
  isView: false,
  title: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DialogProps) => {
  dialogProps.value = params;
  dialogVisible.value = true;
  if (dialogProps.value.title === "批量新增") {
    dialogProps.value.row.startCode = 0;
  }
  if (dialogProps.value.title === "新增") {
    getFoodCouponUserCode().then(res => {
      dialogProps.value.row!.couponCode = res.data;
    });
  }
  getDicData("CouponType").then(couponType => {
    giftVoucherType.value = couponType.data;
  });
};

const onRadio = (row: any) => {
  if (row.index === 0) {
    dialogProps.value.row.typeId = row.data.typeId;
    dialogProps.value.row.couponName = row.data.name;
    dialogProps.value.row.couponId = row.data.id;
    dialogProps.value.row.parValue = row.data.parValue;
  } else if (row.index === 1) {
    dialogProps.value.row.userName = row.data.nickName;
    dialogProps.value.row.userId = row.data.id;
  }
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await dialogProps.value.api!(dialogProps.value.row);
      ElMessage.success({ message: `${dialogProps.value.title}礼券发放成功！` });
      dialogProps.value.getTableList!();
      dialogVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

const selectTableRef = ref<InstanceType<typeof SelectTable> | null>(null);
const openSelectTreeTable = (title: string, ix: number) => {
  const params = {
    title,
    isView: false,
    index: ix,
    selType: "radio",
    columns:
      ix === 0
        ? [
            { type: "radio", label: "单选", width: 60 },
            { prop: "name", label: "优惠券名称", align: "left" },
            {
              prop: "typeId",
              label: "礼券类型",
              align: "left",
              enum: giftVoucherType,
              fieldNames: { label: "title", value: "value" }
            }
          ]
        : [
            { type: "radio", label: "单选", width: 60 },
            {
              prop: "nickName",
              label: "会员名称",
              align: "left",
              search: {
                el: "input",
                span: 2
              }
            },
            { prop: "number", label: "会员卡号", align: "left" },
            { prop: "mobile", label: "电话号码", align: "left" }
          ],
    api: ix === 0 ? getFoodCouponList : getMemberList
  };
  selectTableRef.value?.acceptParams(params);
};

defineExpose({
  acceptParams
});
</script>
